<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
      #canvas {
          border: 1px solid;
      }
  </style>
</head>
<body>
  <canvas id="canvas" width="500" height="500"></canvas>
  <div>
    <button onclick="changeType('circle')">圆形框选</button>
    <button onclick="changeType('rect')">矩形框选</button>
  </div>
</body>

<script>
  const canvas = document.querySelector("#canvas")
  const ctx = canvas.getContext('2d')
  let startX, startY, endX, endY
  let isMoveUp = false
  let type = 'rect'

  function changeType(value) {
    type = value
  }

  canvas.addEventListener("mousedown", event => {
    const { x, y } = event
    startX = x
    startY = y
    isMoveUp = true
    console.log(x, y)
  })

  canvas.addEventListener("mousemove", event => {
    const { x, y } = event
    const {
      x: canvasStartX,
      y: canvasStartY,
      width: canvasWidth,
      height: canvasHeight
    } = canvas.getBoundingClientRect()
    if (x > canvasWidth || y > canvasHeight) {
      endX = x > canvasWidth ? canvasWidth - 2 : x
      endY = y > canvasHeight ? canvasHeight - 2 : y
      if (x > canvasWidth && y > canvasHeight) isMoveUp = false
    } else if (x < canvasStartX || y < canvasStartY) {
      endX = x < canvasStartX ? canvasStartX - 2 : x
      endY = y < canvasStartY ? canvasStartY - 2 : y
      if (x < canvasStartX || y < canvasStartY) isMoveUp = false
    } else {
      endX = x
      endY = y
    }

    if(isMoveUp) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.save();
      ctx.beginPath();
      if (type === 'rect') {
        // 画矩形
        ctx.strokeStyle = '#ff0000';
        ctx.lineWidth = 2;
        ctx.rect(startX, startY, endX - startX, endY - startY);
        ctx.stroke();
        ctx.restore();
      } else {
        // 画圆
        // 拿到开始x，y坐标和结束x，y坐标，通过勾股定理计算圆的半径
        ctx.arc(startX, startY, Math.sqrt(Math.abs(endX - startX) * Math.abs(endX - startX) + Math.abs(endY - startY) * Math.abs(endY - startY)), 0, 2 * Math.PI)
        ctx.stroke();
      }
    }
  })

  canvas.addEventListener('mouseup', () => {
    isMoveUp = false;
    const posX = Math.min(startX, endX);
    const posY = Math.min(startY, endY);
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);

    // 获取裁剪区域的坐标和大小
    // console.log(posX, posY, width, height);
  });
</script>
</html>
